package com.rem.cloudalibaba.service.sentinel;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;


/**
 * @author Rem
 * @date 2021/8/4
 */
@Service
@Slf4j
public class SentinelResourcesService {

    int i = 0;

    /**
     * 直接将限流和降级方法定义在方法中
     *
     * @return
     */
    @SentinelResource(
            value = "resource-message1",
            //指定发生BlockException是 进入的方法
            blockHandler = "blockHandlerMethod",
            //指定发生Throwable时 进入的方法
            fallback = "fallbackMethod"
    )
    public String message() {
        i++;
        if (i % 3 == 0) {
            throw new RuntimeException("我是故意的");
        }
        return "message11111";
    }

    public String blockHandlerMethod(BlockException e) {
        log.error("FlowException:", e);
        return "SentinelResourcesService.message 接口被限流了";
    }

    public String fallbackMethod(Throwable e) {
        log.error("RuntimeException:", e);
        return "接口发生了异常";
    }


    /**
     * 将限流和降级方法外置到单独的类中
     *
     * @return
     */
    @SentinelResource(
            value = "resource-message2",
            blockHandlerClass = SentinelResourcesServiceBlockHandler.class,
            blockHandler = "blockHandlerMethod2",
            fallbackClass = SentinelResourcesServiceFallback.class,
            fallback = "fallbackMethod2"
    )
    public String message2() {
        i++;
        if (i % 3 == 0) {
            throw new RuntimeException("我还是故意的");
        }
        return "message22222";
    }
}
